<!-- 初级认证（终极回显修正版） -->
<script setup>
import { ref, computed, onMounted } from 'vue'
import { uploadKYC } from '@/api/user'
import { uploadImg } from '@/api/common/index.js'
import { _t18 } from '@/utils/public'
import { useToast } from '@/hook/useToast'
import { useUserStore } from '@/store/user/index'
import { showToast, showConfirmDialog } from 'vant'
import { useRouter } from 'vue-router'
import { nation } from './components/nation.js'

const { _toast } = useToast()
const router = useRouter()
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

const primaryAuth = ref('0')
const advancedAuth = ref('0')

const form = ref({
  name: '',
  birthday: '',
  address: '',
  idNumber: '',
  country: ''
})

const nationName = ref('')
const showNation = ref(false)
const nationList = computed(() =>
  nation.map((elem) => ({ ...elem, title: `nation_${elem.name}` }))
)

const fileList1 = ref([])
const fileList2 = ref([])
const fileList3 = ref([])

/** 初始化 */
onMounted(async () => {
  await userStore.getUserInfo()
  initFormData()
})

/** 初始化数据 + 图片回显修复 */
function initFormData() {
  const detail = userInfo.value?.detail || {}
  primaryAuth.value = detail.auditStatusPrimary || '0'
  advancedAuth.value = detail.auditStatusAdvanced || '0'

  if (primaryAuth.value == '2') {
    showConfirmDialog({
      title: _t18('Kind_tips'),
      message: _t18('25_renzhengshibai'),
      confirmButtonText: _t18('btnConfirm'),
      cancelButtonText: _t18('cancel')
    })
      .then(() => {
        resetFormData()
        showToast(_t18('25_chongxintianxieziliao'))
      })
      .catch(() => {
        showToast(_t18('25_baoliuyuanyoushuju'))
      })
  }

  form.value = {
    name: detail.realName || '',
    birthday: detail.birthday || '',
    address: detail.jzAddress || '',
    idNumber: detail.idCard || '',
    country: detail.country || ''
  }
  nationName.value = detail.country || ''

  // ✅ 修复 Vant 回显问题（必须含 url、isImage、status）
  if (detail.frontUrl && detail.frontUrl !== 'undefined') {
    fileList1.value = [
      {
        url: detail.frontUrl,
        res: detail.frontUrl,
        status: 'success',
        isImage: true,
        key: 'front'
      }
    ]
  }
  if (detail.backUrl && detail.backUrl !== 'undefined') {
    fileList2.value = [
      {
        url: detail.backUrl,
        res: detail.backUrl,
        status: 'success',
        isImage: true,
        key: 'back'
      }
    ]
  }
  if (detail.handelUrl && detail.handelUrl !== 'undefined') {
    fileList3.value = [
      {
        url: detail.handelUrl,
        res: detail.handelUrl,
        status: 'success',
        isImage: true,
        key: 'handel'
      }
    ]
  }
}

/** 通用上传函数 */
const uploadCommon = (file, listRef) => {
  file.status = 'uploading'
  const formData = new FormData()
  formData.append('file', file.file)
  uploadImg(formData)
    .then((res) => {
      const data = res.data
      if (data.code == 200 || data.code == '200') {
        const url = data.data?.url || ''
        file.res = url
        file.url = url
        file.isImage = true
        file.status = 'success'
        // ✅ 上传后立即更新预览
        listRef.value = [{ ...file }]
      } else {
        showToast(data.msg)
        listRef.value = []
      }
    })
    .catch(() => {
      showToast(_t18('25_shangchuanshibai'))
      listRef.value = []
    })
}

const afterRead1 = (file) => uploadCommon(file, fileList1)
const afterRead2 = (file) => uploadCommon(file, fileList2)
const afterRead3 = (file) => uploadCommon(file, fileList3)

/** 重置 */
function resetFormData() {
  form.value = { name: '', birthday: '', address: '', idNumber: '', country: '' }
  nationName.value = ''
  fileList1.value = []
  fileList2.value = []
  fileList3.value = []
}

/** 国家选择 */
const onSelectNation = (item) => {
  showNation.value = false
  nationName.value = item.name
}

/** 提交 */
/** 提交 */
const submit = () => {
  if (!form.value.name) return _toast('advanced_please_name')
  if (!form.value.idNumber) return _toast('advanced_please_number')
  if (!nationName.value) return _toast('advanced_please_country')

  const f1 = fileList1.value[0] || {}
  const f2 = fileList2.value[0] || {}
  const f3 = fileList3.value[0] || {}
  const flag = primaryAuth.value === '1' ? 2 : 1

  // ✅ 当 auditStatusPrimary = 1 时，必须上传正反面
  if (primaryAuth.value === '1') {
    if (!f1.res || f1.status !== 'success') {
      return _toast('loan_front')
    }
    if (!f2.res || f2.status !== 'success') {
      return _toast('loan_reverse')
    }
  }

  const params = `realName=${form.value.name}&idCard=${form.value.idNumber}&flag=${flag}&frontUrl=${f1.res || ''}&backUrl=${f2.res || ''}&country=${nationName.value}&handelUrl=${f3.res || ''}&cardType=1&jzAddress=${form.value.address}&birthday=${form.value.birthday}`

  uploadKYC(params)
    .then((res) => {
      if (res.code == 200 || res.code == '200') {
        _toast('please_wait')
        router.push('/auth-center')
      } else {
        showToast(res.msg)
      }
    })
   .catch(() => showToast(_t18('25_shangchuanshibai')))
}

</script>

<template>
  <TopNavBar :title="_t18('24_auth')" type="back" />

  <div class="certification-form-bg">
    <div class="certification-form" v-if="primaryAuth != '1' || advancedAuth == '1'">
      <div class="form-item">
        <label>{{ _t18('advanced_name') }}</label>
        <input v-model="form.name" type="text" :placeholder="_t18('advanced_please_name')"  :readonly="primaryAuth === '1'"/>
      </div>
      <div class="form-item">
        <label>{{ _t18('advanced_IdCard') }}</label>
        <input v-model="form.idNumber" type="text" :placeholder="_t18('advanced_please_cardName')"  :readonly="primaryAuth === '1'"/>
      </div>
     <div class="form-item">
        <label>{{ _t18('25_guojia') }}</label>
        <van-cell
          style="margin-top: 30px"
          is-link
          :title="_t18(nationName)"
		  :readonly="primaryAuth === '1'"
          :class="{ disabled: primaryAuth === '1' }"
            @click="primaryAuth !== '1' && (showNation = true)"
        />
        <van-action-sheet
          v-model:show="showNation"
          :actions="nationList"
          @select="onSelectNation"
          style="max-width: var(--ex-max-width); left: 50%; translate: -50%"
        >
          <template #action="{ action, index }">
            <div :key="index">{{ _t18(action.title) }}</div>
          </template>
        </van-action-sheet>
      </div>
    </div>

    <div class="upload-section">
      <div class="upload-card-group">
		  <p class="auth-warning" v-if="primaryAuth == '1'&& advancedAuth != '1'">{{ _t18('25_jixurenzheng') }}</p>
         <div class="upload-card" v-if="primaryAuth == '1'">  
          <van-uploader v-model="fileList1" :after-read="afterRead1"  :deletable="advancedAuth != '1'" >
            <template v-if="!fileList1.length">
              <image-load filePath="/static/img/ZBa_ebe8dd2f_PWk.png" class="img" />
              <div class="tit">{{ _t18('loan_idcardFront') }}</div>
            </template>
          </van-uploader>
        </div>

         <div class="upload-card" v-if="primaryAuth == '1'">
          <van-uploader v-model="fileList2" :after-read="afterRead2"  :deletable="advancedAuth != '1'"  >
            <template v-if="!fileList2.length">
              <image-load filePath="/static/img/ZBa_ebe8dd2f_PWk.png" class="img" />
              <div class="tit">{{ _t18('loan_idcardReverse') }}</div>
            </template>
          </van-uploader>
        </div>

        <!--<div class="upload-card" v-if="primaryAuth == '1'">
          <van-uploader v-model="fileList3" :after-read="afterRead3">
            <template v-if="!fileList3.length">
              <image-load filePath="/static/img/ZBa_ebe8dd2f_PWk.png" class="img" />
              <div class="tit">請上傳手持身份證</div>
            </template>
          </van-uploader>
        </div>-->
      </div>

      <button class="submit-btn" v-if="primaryAuth == '3'">{{ _t18('recharge_waiting') }}</button>
      <button class="submit-btn" v-else-if="advancedAuth == '1'">{{ _t18('advanced_success') }}</button>
      <button class="submit-btn" v-else @click="submit">{{ _t18('advanced_submit') }}</button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.certification-form-bg {
  background: #f3f6f9;
  min-height: 100vh;
  padding: 0 16px;
}
.certification-form {
  padding: 24px 0 0 0;
  width: 100%;
  max-width: 430px;
  margin: 0 auto;
  .form-item {
    margin-bottom: 32px;
    label {
      display: block;
      font-weight: bold;
      margin-bottom: 8px;
      color: #111;
      font-size: 17px;
    }
    input[type='text'] {
      width: 100%;
      height: 52px;
      padding: 0 18px;
      border: none;
      border-radius: 10px;
      background: #f7f9fa;
      font-size: 16px;
      color: #333;
      box-shadow: 0 0 0 2px #e0e6ed;
      &::placeholder {
        color: #bfc5cc;
      }
    }
  }
}

.upload-section {
  margin-top: 18px;
  .upload-card-group {
    display: flex;
    flex-direction: column;
    gap: 18px;
    margin-bottom: 28px;
  }
  .upload-card {
    position: relative;
    background: #fff;
    border-radius: 18px;
    min-height: 140px;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    text-align: center;
    :deep(.van-uploader__wrapper) {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      .img {
        width: 50px;
        height: 50px;
        opacity: 0.6;
      }
      .tit {
        color: #bca48a;
        font-size: 15px;
        margin-top: 6px;
      }
      .van-uploader__preview {
        width: 100%;
        height: 100%;
      }
      .van-uploader__preview-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }
  .submit-btn {
    width: 100%;
    height: 48px;
    background: #111;
    color: #fff;
    border: none;
    border-radius: 24px;
    font-size: 18px;
    font-weight: bold;
    margin-top: 8px;
  }
}
.auth-warning {
  color: #ff4d4f; /* 🔴 红色警告文字 */
  font-size: 15px;
  font-weight: 600;
  text-align: center;
  margin-bottom: 10px;
  letter-spacing: 0.5px;
}

</style>
